package com.weiyv.Updater.utils;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.FileOutputStream;
import java.io.InputStream;

public class DownloadAPK extends AsyncTask<String, Integer, String> {
    private final String TAG = "WeiyvUpdater";
    private Context context;
    private Runnable callBack;

    public DownloadAPK(Context context,Runnable callBack){
        super();
        this.context = context;
        this.callBack = callBack;
    }

    @Override
    protected void onPreExecute() {
        Log.i(TAG, "Starting download apk files.");
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            String fileURL = params[0];
            String appPath = context.getFilesDir().toString();
            String fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1);
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(fileURL);
                HttpResponse response = client.execute(get);
                if (response.getStatusLine().getStatusCode() != 200) {
                    Log.i(TAG, "http error when download update package. from " + fileURL);
                    return null;
                }
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                if (is == null)
                    return null;
                FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_WORLD_READABLE);
                byte[] buf = new byte[8196];
                int read;
                while ((read = is.read(buf)) != -1) {
                    fileOutputStream.write(buf, 0, read);
                }
                is.close();
                fileOutputStream.close();
            return appPath + "/" + fileName;
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        Log.i(TAG, "Download complete");
    }
}
